package com.eboss2.sbs.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.RelativeLayout;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.core.FyBat;
import com.eboss2.sbs.core.ZfQbAction;
import com.eboss2.sbs.enums.EnumConsts;
import com.eboss2.sbs.http.API;
import com.eboss2.sbs.http.HttpCallback;
import com.eboss2.sbs.interfaces.ActionCallbackListener;
import com.eboss2.sbs.model.CaculateMoneyEntity;
import com.eboss2.sbs.model.MemberBenifitEntity;
import com.eboss2.sbs.model.UploadResultEntity;
import com.eboss2.sbs.model.db.OrderDetail;
import com.eboss2.sbs.model.fuyou.FyMicropayResponse;
import com.eboss2.sbs.model.fuyou.FyQueryResponse;
import com.eboss2.sbs.model.fuyou.FyRefundResponse;
import com.eboss2.sbs.model.qianbao.ZfQbResponse;
import com.eboss2.sbs.myapplication.MyApplication;
import com.google.gson.reflect.TypeToken;
import com.mytools.tool.activityManager.MyActivityManager;
import com.mytools.tool.utils.LocalParasUtils;
import com.mytools.tool.utils.LogUtils;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.utils.StringUtils;
import com.mytools.tool.utils.SystemUtil;
import com.mytools.tool.utils.TimeUtil;
import com.mytools.tool.views.MyDialog;
import com.tool.utils.dialog.LoadingDialog;
import com.tool.utils.dialog.PassWordDialog;
import com.tool.utils.systemUtils.SystemUtils;
import com.tool.utils.utils.SPUtils;
import com.tool.utils.utils.ToastUtils;
import com.tool.utils.utils.UtilPreference;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PayChannelChooseActivity extends BaseActivity implements View.OnClickListener{

    public static String CACULATE_MONEY_ENTITY = "CACULATE_MONEY_ENTITY";

    private static final int REQUEST_FY_CAPTURE_WX = 0;
    private static final int REQUEST_FY_CAPTURE_ALY = 1;
    private static final int REQUEST_ZF_CAPTURE_QB = 2;

    private String password;
    private String couponSns;
    private int pointAmount;

    private CaculateMoneyEntity caculateMoneyEntity;
    private int pay_channel = 0;

    private FyBat fybat;        //fuyou
    private ZfQbAction qb;      //qianbao

    private int scanPayType;// = ScanPayType.SQB.getType();
    private String groundId;

    private String orderNo;

    private PassWordDialog dialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_pay_channel_choose);
        MyActivityManager.getInstance().addActivity(this);
//        scanPayType = mApp.getLoginEntity().getScanPayType();

        caculateMoneyEntity = (CaculateMoneyEntity) getIntent().getSerializableExtra(CACULATE_MONEY_ENTITY);
        password = getIntent().getStringExtra("password");
        couponSns = getIntent().getStringExtra("couponSns");
        pointAmount = getIntent().getIntExtra("pointAmount", 0);

        initView();

        fybat = new FyBat(this, UtilPreference.getStringValue(mContext, "mid"), new PayResultEvent());
        qb = new ZfQbAction(this);




    }

    /**
     * 富友扫码支付成功后回调这里
     *
     * @author bxq
     */
    class PayResultEvent implements FyBat.FYPayResultEvent {
        @Override
        public void onSuccess(FyMicropayResponse data, String client_sn) {
            doSubmit(client_sn, data.getTransaction_id(), data.getMchnt_order_no());

        }

        @Override
        public void onSuccess(FyQueryResponse data, String client_sn) {
            doSubmit(client_sn, data.getTransaction_id(), data.getMchnt_order_no());
        }

        @Override
        public void onFailure(int statusCode, String error_msg, String client_sn) {
        }

        @Override
        public void onSuccess(FyRefundResponse data, String client_sn) {
        }
    }



    private void initView() {


        RelativeLayout relativeLayout = relativeLayout(R.id.lv_heard);
        relativeLayout.setBackgroundColor(getResources().getColor(R.color.statusBar));
        setTvText(R.id.tv_title, "选择支付渠道");

        setTvText(R.id.tv_trade_money, "￥"+StringUtils.formatStrMoney(caculateMoneyEntity.getTradeMoney()+"") );
        setTvText(R.id.tv_point_money, "￥"+StringUtils.formatStrMoney(caculateMoneyEntity.getPointCoverMoney()+"") );
        setTvText(R.id.tv_coupon_money, "￥"+StringUtils.formatStrMoney(caculateMoneyEntity.getCouponCoverMoney()+"") );
        setTvText(R.id.tv_real_money, "￥"+StringUtils.formatStrMoney(caculateMoneyEntity.getRealMoney()+""));

        int realMoney = caculateMoneyEntity.getRealMoney();
        showView(R.id.layout_channels, realMoney != 0);
        showView(R.id.layout_channels2, realMoney != 0);
        showView(R.id.layout_cash_pay, realMoney == 0);

        findViewById(R.id.layout_alipay).setOnClickListener(this);
        findViewById(R.id.layout_weixin).setOnClickListener(this);
        findViewById(R.id.layout_qb).setOnClickListener(this);
//        findViewById(R.id.layout_baidu).setOnClickListener(this);
//        findViewById(R.id.layout_jingdong).setOnClickListener(this);
        findViewById(R.id.layout_pay_cash).setOnClickListener(this);
//        findViewById(R.id.layout_pay_card).setOnClickListener(this);
        findViewById(R.id.titleback_btn_back).setOnClickListener(this);
        findViewById(R.id.btn_cash_pay).setOnClickListener(this);
        findViewById(R.id.layout_stk).setOnClickListener(this);

        if (StringUtils.isBlank(caculateMoneyEntity.getMemberCardNo())) {
            linearLayout(R.id.ll_member_show).setVisibility(View.GONE);
        }else{
            linearLayout(R.id.ll_member_show).setVisibility(View.VISIBLE);
        }

        EventBus.getDefault().register(this);

    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getOrderNo(String event){
        orderNo = event;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册 , 防止Activity内存泄漏
        EventBus.getDefault().unregister( this ) ;


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setOrderCancel();
    }

    private void setOrderCancel(){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderNo", orderNo);
        API.http_post(this, API.ORDER_CANCEL, params, null);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_alipay:
                pay_channel = EnumConsts.SqbPayChannel.ALIPAY.getType();
//                if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
////                    execute_sqb();
//                } else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
//                    execute_fuyou();
//                    //toast("富友-支付宝-收款");
//                }
                execute_fuyou();
                break;
            case R.id.layout_weixin:

                pay_channel = EnumConsts.SqbPayChannel.WEIXIN.getType();
//                if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
////                    execute_sqb();
//                } else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
//                    execute_fuyou();
//                    //toast("富友-微信-收款");
//                }
                execute_fuyou();
                break;
            case R.id.layout_qb:
                pay_channel = EnumConsts.SqbPayChannel.WALLET.getType();
                scanPayType = EnumConsts.ScanPayType.WALLET.getType();
                execute_qb();
                break;
            case R.id.layout_stk:
                pay_channel = EnumConsts.SqbPayChannel.STKPAY.getType();
                if (caculateMoneyEntity != null && StringUtils.isBlank(caculateMoneyEntity.getStkCardNo())){
                    ToastUtils.CustomShow(mContext, "请选择其他支付方式");
                    return;
                }
                inputCardPass();
                break;
//			case R.id.layout_baidu:
//				pay_channel = SqbPayChannel.BAIDU.getType();
//				execute();
//				break;
//			case R.id.layout_jingdong:
//				pay_channel = SqbPayChannel.JINGDONG.getType();
//				execute();
//				break;
            case R.id.titleback_btn_back:
                onBackPressed();
                break;
            case R.id.layout_pay_cash:
                Intent intent1 = new Intent(mContext, PayCashActivity.class);
                intent1.putExtra(PayCashActivity.CACULATE_MONEY_ENTITY, caculateMoneyEntity);
                intent1.putExtra("password", password);
                intent1.putExtra("couponSns", couponSns);
                intent1.putExtra("pointAmount", pointAmount);
                intent1.putExtra("orderNo", orderNo);
                startActivity(intent1);
                //finish();
                break;
//            case R.id.layout_pay_card:
//                Intent intent2 = new Intent(mContext, PayCardActivity.class);
//                intent2.putExtra(PayCashActivity.CACULATE_MONEY_ENTITY, caculateMoneyEntity);
//                intent2.putExtra("password", password);
//                intent2.putExtra("couponSns", couponSns);
//                intent2.putExtra("pointAmount", pointAmount);
//                intent2.putExtra("orderNo", orderNo);
//                startActivity(intent2);
//                //finish();
//                break;
            case R.id.btn_cash_pay:
                MyDialog dialog;
                MyDialog.Builder builder = new MyDialog.Builder(this);
                builder.setTitle("提示");
                builder.setMessage("确认交易完成？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        pay_cash_zero_submit();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        dialog.dismiss();
                    }
                });


                dialog = builder.create();
//                dialog.setCancelable(false);
                dialog.show();

//                builder.create().show();
                break;
            default:
                break;
        }
    }



    /**
     * 实体卡密码支付
     */
    private void inputCardPass() {
        dialog = new PassWordDialog(mContext, R.layout.activity_psw, new PassWordDialog.OnResultInterface() {

            @Override
            public void onResult(String data) {
                LogUtils.e(data);
                dialog.dismiss();
                ZfStkPay(data);
            }
        });
        dialog.setCancelable(true);
        dialog.show();
    }

    /**
     * 钱包支付
     * @param result
     */
    private void ZfStkPay(String result) {

        final long t = new Date().getTime();
        final String traceNum = StringUtils.getFormatCurTime() + StringUtils.createRandomNumStr(5);
        final Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("sid", MyApplication.getmInstance().getLoginMEntity().getShopid());
        String memberCardNo = caculateMoneyEntity.getMemberCardNo();
        if (!StringUtil.isNull(memberCardNo)) {
            paramsMap.put("cardNo", memberCardNo);
        } else {
            paramsMap.put("cardNo", "");
        }
        paramsMap.put("orderNo", orderNo);
        paramsMap.put("activateCode", SystemUtils.getIMEI(mContext));
        paramsMap.put("merchantNo", "");
        paramsMap.put("serialNum",SystemUtils.getIMEI(mContext));
        paramsMap.put("payPassword", result);
        paramsMap.put("operator_num", "01");
        paramsMap.put("couponCoverAmount", caculateMoneyEntity.getCouponCoverMoney());
        paramsMap.put("pointCoverAmount", caculateMoneyEntity.getPointCoverMoney());
        paramsMap.put("couponSns", couponSns);
        paramsMap.put("pointAmount", pointAmount);
        paramsMap.put("payAmount", caculateMoneyEntity.getRealMoney());
        paramsMap.put("t", t);
        paramsMap.put("transNo", traceNum);

        API.http_post(this, API.IC_CARD_PAY, paramsMap, new HttpCallback<UploadResultEntity>(this) {
            @Override
            public void onSuccess(int statusCode, UploadResultEntity data) {
                saveLocalTradeDetail(t, orderNo, traceNum, "");
                updateOrderDetail(orderNo, data);
                openConfirmDialog(pay_channel);
            }

            @Override
            public void onFailure(int statusCode, String message) {
//                openConfirmDialog(pay_channel);
                super.onFailure(statusCode, message);
            }

            @SuppressWarnings({ "unchecked", "rawtypes" })
            @Override
            public TypeToken getTypeToken() {
                return new TypeToken<UploadResultEntity>() {};
            }
        });

    }







    /**
     * 积分或者优惠券抵消后，实际支付为0的情况
     */
    private void pay_cash_zero_submit() {

//        final String clientOrderNo = PayChannelChooseActivity.getNewClientSn(mContext, EnumConsts.SqbPayChannel.CASH_MEMO.getType(), scanPayType);
        long t = new Date().getTime();

        saveLocalTradeDetail_paycash_zero(t, orderNo);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sid", MyApplication.getmInstance().getLoginMEntity().getShopid());
        String memberCardNo = caculateMoneyEntity.getMemberCardNo();
        if (!StringUtil.isNull(memberCardNo)) {
            params.put("cardNo", memberCardNo);
        } else {
            params.put("cardNo", "");
        }
        if (!StringUtil.isNull(password)) {
            params.put("password", password);
        } else {
            params.put("password", "");
        }
        if (!StringUtil.isNull(couponSns)) {
            params.put("couponSns", couponSns);
        } else {
            params.put("couponSns", "");
        }

        params.put("cash", caculateMoneyEntity.getRealMoney());
        params.put("bankAmount", "");
        params.put("couponCoverAmount", caculateMoneyEntity.getCouponCoverMoney());
        params.put("pointCoverAmount", caculateMoneyEntity.getPointCoverMoney());
        params.put("clientOrderNo", orderNo);
        //params.put("terminalNo", PayChannelChooseActivity.getActivateCodeId(this));

//        //收钱吧
//        if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
//            params.put("activateCode", LocalParasUtils.getActivateCode(this));
//            params.put("merchantNo", LocalParasUtils.getMerchantNo(this));
//        }
//        //富友
//        else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
////            params.put("activateCode", mApp.getLoginEntity().getActivateCode());
////            params.put("merchantNo", mApp.getLoginEntity().getFyMerchantNo());
//        }

        params.put("activateCode",UtilPreference.getStringValue(mContext, "tid"));
        params.put("merchantNo", UtilPreference.getStringValue(mContext, "mid"));
        params.put("scanOrganization", UtilPreference.getIntValue(mContext, "scanOrganization", 0));

        params.put("t", t);
        params.put("transNo", "");
        params.put("authCode", "");
        params.put("pointAmount", pointAmount);

        params.put("serialNum", SystemUtils.getIMEI(mContext));
        params.put("payType", EnumConsts.SqbPayChannel.CASH_MEMO.getType());

        API.http_post(this, API.TRADE_LOG_UPLOAD, params, new HttpCallback<UploadResultEntity>(this) {
            @Override
            public void onSuccess(int statusCode, UploadResultEntity data) {
                updateOrderDetail(orderNo, data);
                openConfirmDialog(EnumConsts.SqbPayChannel.CASH_MEMO.getType());
            }

            @Override
            public void onFailure(int statusCode, String message) {
                openConfirmDialog(EnumConsts.SqbPayChannel.CASH_MEMO.getType());
                super.onFailure(statusCode, message);
            }

            @SuppressWarnings({"unchecked", "rawtypes"})
            @Override
            public TypeToken getTypeToken() {
                return new TypeToken<UploadResultEntity>() {
                };
            }
        });
    }

    /**
     * 当支付金额减去优惠金额，结果为0时，本地流水记录保存
     *
     * @param t
     * @param tradeOrderNo
     */
    private void saveLocalTradeDetail_paycash_zero(long t, String tradeOrderNo) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSid(MyApplication.getmInstance().getLoginMEntity().getShopid());
        orderDetail.setTradeOrderNo(tradeOrderNo);
        orderDetail.setPayType(EnumConsts.SqbPayChannel.CASH_MEMO.getType());

        orderDetail.setState(EnumConsts.SqbPayState.SUCCESS.getType());
        orderDetail.setTradeMoney(caculateMoneyEntity.getTradeMoney());
        orderDetail.setRealMoney(caculateMoneyEntity.getRealMoney());
        orderDetail.setMemberName(caculateMoneyEntity.getMemberName());
        //orderDetail.setPointCost(caculateMoneyEntity.getPointCoverMoney());

        int couponCoverMoney = caculateMoneyEntity.getCouponCoverMoney();
        int pointCoverMoney = caculateMoneyEntity.getPointCoverMoney();
        String couponString = couponCoverMoney == 0 ? "" : ("优惠券抵消" + StringUtil.getMoneyString(couponCoverMoney) + "元;");
        String pointString = pointCoverMoney == 0 ? "" : ("积分抵消" + StringUtil.getMoneyString(pointCoverMoney) + "元;");

        if (!StringUtil.isNull(couponString) && !StringUtil.isNull(pointString)) {
            orderDetail.setBenefit(pointString + couponString);
        } else if (StringUtil.isNull(couponString) && !StringUtil.isNull(pointString)) {
            orderDetail.setBenefit(pointString);
        } else if (!StringUtil.isNull(couponString) && StringUtil.isNull(pointString)) {
            orderDetail.setBenefit(couponString);
        } else {
            orderDetail.setBenefit("");
        }

        orderDetail.setTradeTime(t);
        if (!StringUtil.isNull(password)) {
            orderDetail.setPassword(password);
        }
        if (!StringUtil.isNull(couponSns)) {
            orderDetail.setCouponSns(couponSns);
        }
        String memberCardNo = caculateMoneyEntity.getMemberCardNo();
        if (!StringUtil.isNull(memberCardNo)) {
            orderDetail.setCardNo(memberCardNo);
        }


//        //收钱吧
//        if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
//            orderDetail.setTerminalSn("" + LocalParasUtils.getActivateCode(mContext));
//            orderDetail.setMerchantNo(LocalParasUtils.getMerchantNo(mContext));
//            orderDetail.setActivateCode(LocalParasUtils.getActivateCode(mContext));
//            orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mContext));
//        }
//        //富友
//        else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
////            orderDetail.setTerminalSn(mApp.getLoginEntity().getFyMerchantNo());
////            orderDetail.setMerchantNo(mApp.getLoginEntity().getFyMerchantNo());
////            orderDetail.setActivateCode(mApp.getLoginEntity().getActivateCode());
////            orderDetail.setTerminalName(mApp.getLoginEntity().getFyMerchantName());
//        }
        orderDetail.setTerminalSn(UtilPreference.getStringValue(mContext, "mid"));
        orderDetail.setMerchantNo(UtilPreference.getStringValue(mContext, "mid"));
        orderDetail.setActivateCode(UtilPreference.getStringValue(mContext, "tid"));
        orderDetail.setTerminalName(UtilPreference.getStringValue(mContext, "merchantName"));
        orderDetail.setPointAmount(pointAmount);

        orderDetail.setCash(0);
        orderDetail.setBankAmount(0);

        TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        orderDetail.setSerialNum(tm.getDeviceId());
        orderDetail.save();
    }


    //fuyou scan pay
    private void execute_fuyou() {
        if (pay_channel == EnumConsts.SqbPayChannel.ALIPAY.getType()) {
            startActivityForResult(new Intent(mContext, CaptureActivity.class), REQUEST_FY_CAPTURE_ALY);
        } else if (pay_channel == EnumConsts.SqbPayChannel.WEIXIN.getType()) {
            startActivityForResult(new Intent(mContext, CaptureActivity.class), REQUEST_FY_CAPTURE_WX);
        }
    }

    //qb scan pay
    private void execute_qb() {
        startActivityForResult(new Intent(mContext, CaptureActivity.class), REQUEST_ZF_CAPTURE_QB);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            //富友扫码_微信
            case REQUEST_FY_CAPTURE_WX:
                String result_wx = data.getStringExtra(CodeUtils.RESULT_STRING);
                //Log.e("result", result_wx);
                //fybat.set
//                String client_sn_1 = getNewClientSn(mContext, pay_channel, scanPayType);
                fybat.pay(orderNo, result_wx, EnumConsts.FYScanChannel.PAY_FY_WX.getChannel(), caculateMoneyEntity.getRealMoney());
                break;
            //富友扫码_支付宝
            case REQUEST_FY_CAPTURE_ALY:
                String result_aly = data.getStringExtra(CodeUtils.RESULT_STRING);
                //Log.e("result", result_aly);
//                String client_sn_2 = getNewClientSn(mContext, pay_channel, scanPayType);
                fybat.pay(orderNo, result_aly, EnumConsts.FYScanChannel.PAY_FY_ALY.getChannel(), caculateMoneyEntity.getRealMoney());
                break;
            case REQUEST_ZF_CAPTURE_QB:
                String result_qb = data.getStringExtra(CodeUtils.RESULT_STRING);
                ZfQbPay(result_qb);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 钱包支付
     * @param result_qb
     */
    private void ZfQbPay(String result_qb) {

        if (StringUtils.isEmpty(result_qb)) {
            toast("获取扫码信息为空");
            return;
        }
        final String temp[] = result_qb.split("&");
        final long t = new Date().getTime();
        final String traceNum = com.tool.utils.utils.StringUtils.getFormatCurTime() + com.tool.utils.utils.StringUtils.createRandomNumStr(5);
        final Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("sid", MyApplication.getmInstance().getLoginMEntity().getShopid());
        paramsMap.put("qrCode", temp[0]);
        paramsMap.put("cardNo",  temp[1]);
        paramsMap.put("orderNo", orderNo);
        paramsMap.put("activateCode", SystemUtils.getIMEI(mContext));
        paramsMap.put("merchantNo", "");
        paramsMap.put("serialNum",SystemUtils.getIMEI(mContext));
        paramsMap.put("payPassword", "");
        paramsMap.put("operator_num", "01");
        paramsMap.put("couponCoverAmount", caculateMoneyEntity.getCouponCoverMoney());
        paramsMap.put("pointCoverAmount", caculateMoneyEntity.getPointCoverMoney());
        paramsMap.put("couponSns", couponSns);
        paramsMap.put("pointAmount", pointAmount);
        paramsMap.put("payAmount", caculateMoneyEntity.getRealMoney());
        paramsMap.put("t", t);
        paramsMap.put("transNo", traceNum);

        API.http_post(this, API.QB_PAY, paramsMap, new HttpCallback<UploadResultEntity>(this) {
            @Override
            public void onSuccess(int statusCode, UploadResultEntity data) {
                saveLocalTradeDetail(t, orderNo, traceNum, "");
                updateOrderDetail(orderNo, data);
                openConfirmDialog(pay_channel);
            }

            @Override
            public void onFailure(int statusCode, String message) {
                openConfirmDialog(pay_channel);
                super.onFailure(statusCode, message);
            }

            @SuppressWarnings({ "unchecked", "rawtypes" })
            @Override
            public TypeToken getTypeToken() {
                return new TypeToken<UploadResultEntity>() {};
            }
        });

    }



    /**
     * * 收钱吧/富友扫码支付成功后上传
     *
     * @param client_sn 客户端生成订单号
     * @param trade_no  交易流水号（第三方）
     * @param sn        交易机构订单号（富友/收钱吧）
     */
    private void doSubmit(final String client_sn, String trade_no, String sn) {

        long t = new Date().getTime();
        saveLocalTradeDetail(t, client_sn, trade_no, sn);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sid", MyApplication.getmInstance().getLoginMEntity().getShopid());
        String memberCardNo = caculateMoneyEntity.getMemberCardNo();
        if (!StringUtil.isNull(memberCardNo)) {
            params.put("cardNo", memberCardNo);
        } else {
            params.put("cardNo", "");
        }
        if (!StringUtil.isNull(password)) {
            params.put("password", password);
        } else {
            params.put("password", "");
        }
        if (!StringUtil.isNull(couponSns)) {
            params.put("couponSns", couponSns);
        } else {
            params.put("couponSns", "");
        }

        params.put("cash", 0);
        params.put("bankAmount", caculateMoneyEntity.getRealMoney());
        params.put("couponCoverAmount", caculateMoneyEntity.getCouponCoverMoney());
        params.put("pointCoverAmount", caculateMoneyEntity.getPointCoverMoney());
        params.put("clientOrderNo", client_sn);

//        //收钱吧
//        if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
//            params.put("activateCode", LocalParasUtils.getActivateCode(this));
//            params.put("merchantNo", LocalParasUtils.getMerchantNo(this));
//        }
//        //富友
//        else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
//            //富友
////            params.put("activateCode", mApp.getLoginEntity().getActivateCode());
////            params.put("merchantNo", mApp.getLoginEntity().getFyMerchantNo());
//        }
//
//        //钱包
//        if (scanPayType == EnumConsts.ScanPayType.WALLET.getType()) {
//
////            if (EnumConsts.ScanPayType.SQB.getType() == mApp.getLoginEntity().getScanPayType()) {
////                params.put("activateCode", LocalParasUtils.getActivateCode(this));
////                params.put("merchantNo", StringUtil.isNull(groundId) ? "" : groundId);
////
////            } else if (EnumConsts.ScanPayType.FUYOU.getType() == mApp.getLoginEntity().getScanPayType()) {
////                params.put("activateCode", mApp.getLoginEntity().getActivateCode());
////                params.put("merchantNo", StringUtil.isNull(groundId) ? "" : groundId);
////            }
//        }else{
//            params.put("activateCode",UtilPreference.getStringValue(mContext, "tid"));
//            params.put("merchantNo", UtilPreference.getStringValue(mContext, "mid"));
//            params.put("scanOrganization", UtilPreference.getIntValue(mContext, "scanOrganization", 0));
//        }

        params.put("activateCode",UtilPreference.getStringValue(mContext, "tid"));
        params.put("merchantNo", UtilPreference.getStringValue(mContext, "mid"));
        params.put("scanOrganization", UtilPreference.getIntValue(mContext, "scanOrganization", 0));

        params.put("pointAmount", pointAmount);
        params.put("t", t);

        params.put("transNo", trade_no);    //交易流水号（第三方）
        params.put("authCode", sn);            //交易机构订单号（收钱吧）

        params.put("serialNum", SystemUtils.getIMEI(mContext));
        params.put("payType", pay_channel);

        API.http_post(this, API.TRADE_LOG_UPLOAD, params, new HttpCallback<UploadResultEntity>(this) {

            @Override
            public void onSuccess(int statusCode, UploadResultEntity data) {
                updateOrderDetail(client_sn, data);
                openConfirmDialog(pay_channel);
            }

            @Override
            public void onFailure(int statusCode, String message) {
                openConfirmDialog(pay_channel);
                super.onFailure(statusCode, message);
            }

            @SuppressWarnings({"unchecked", "rawtypes"})
            @Override
            public TypeToken getTypeToken() {
                return new TypeToken<UploadResultEntity>() {
                };
            }
        });
    }

    /**
     * 收钱吧扫码支付成功并上传服务器流水后，用返回的内容更新本地保存的交易记录（主要是更新交易返回的积分和优惠券二维码）
     */
    private void updateOrderDetail(String clientOrderNo, UploadResultEntity data) {
        ContentValues cv = new ContentValues();
        String point_url = data.getPoint_url();
//        String coupon_url = data.getCoupon();
        cv.put("point_url", StringUtil.isNull(point_url) ? "" : point_url);
//        cv.put("coupon_url", StringUtil.isNull(coupon_url) ? "" : coupon_url);
        int point = data.getPoint();
        int pointCurrent = data.getPointCurrent();
        cv.put("point", point);
        cv.put("pointCurrent", pointCurrent);

        DataSupport.updateAll(OrderDetail.class, cv, "tradeOrderNo = ?", clientOrderNo);
    }

    private void saveLocalTradeDetail(long t, String tradeOrderNo, String trade_no, String sn) {

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSid(MyApplication.getmInstance().getLoginMEntity().getShopid());
        orderDetail.setTradeOrderNo(tradeOrderNo);
        orderDetail.setPayType(pay_channel);
        orderDetail.setState(EnumConsts.SqbPayState.SUCCESS.getType());
        orderDetail.setTradeMoney(caculateMoneyEntity.getTradeMoney());
        orderDetail.setRealMoney(caculateMoneyEntity.getRealMoney());
        orderDetail.setMemberName(caculateMoneyEntity.getMemberName());

//        //收钱吧
//        if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
//            orderDetail.setTerminalSn(LocalParasUtils.getActivateCode(mContext));
//            orderDetail.setMerchantNo(LocalParasUtils.getMerchantNo(mContext));
//            orderDetail.setActivateCode(LocalParasUtils.getActivateCode(mContext));
//            orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mContext));
//        }
//        //富友
//        else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
////            orderDetail.setTerminalSn(mApp.getLoginEntity().getFyMerchantNo());
////            orderDetail.setMerchantNo(mApp.getLoginEntity().getFyMerchantNo());
////            orderDetail.setActivateCode(mApp.getLoginEntity().getActivateCode());
////            orderDetail.setTerminalName(mApp.getLoginEntity().getFyMerchantName());
//        }
//
//        //钱包
//        else if (scanPayType == EnumConsts.ScanPayType.WALLET.getType()){
//            orderDetail.setTerminalSn(StringUtil.isNull(groundId) ? "":groundId);
//            orderDetail.setMerchantNo(StringUtil.isNull(groundId) ? "":groundId);
////            if (EnumConsts.ScanPayType.SQB.getType() == mApp.getLoginEntity().getScanPayType()){
////                orderDetail.setActivateCode(LocalParasUtils.getActivateCode(mContext));
////                orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mContext));
////            }else if (EnumConsts.ScanPayType.FUYOU.getType() == mApp.getLoginEntity().getScanPayType()){
////                orderDetail.setActivateCode(mApp.getLoginEntity().getActivateCode());
////                orderDetail.setTerminalName(mApp.getLoginEntity().getFyMerchantName());
////            }
//
//        }

        orderDetail.setTerminalSn(UtilPreference.getStringValue(mContext, "mid"));
        orderDetail.setMerchantNo(UtilPreference.getStringValue(mContext, "mid"));
        orderDetail.setActivateCode(UtilPreference.getStringValue(mContext, "tid"));
        orderDetail.setTerminalName(UtilPreference.getStringValue(mContext, "merchantName"));

        int couponCoverMoney = caculateMoneyEntity.getCouponCoverMoney();
        int pointCoverMoney = caculateMoneyEntity.getPointCoverMoney();
        String couponString = couponCoverMoney == 0 ? "" : ("优惠券抵消" + StringUtil.getMoneyString(couponCoverMoney) + "元;");
        String pointString = pointCoverMoney == 0 ? "" : ("积分抵消" + StringUtil.getMoneyString(pointCoverMoney) + "元;");
        if (!StringUtil.isNull(couponString) || !StringUtil.isNull(pointString))
            orderDetail.setBenefit(pointString + couponString);

        orderDetail.setTradeTime(t);
        if (!StringUtil.isNull(password)) {
            orderDetail.setPassword(password);
        }
        if (!StringUtil.isNull(couponSns)) {
            orderDetail.setCouponSns(couponSns);
        }
        String memberCardNo = caculateMoneyEntity.getMemberCardNo();
        if (!StringUtil.isNull(memberCardNo)) {
            orderDetail.setCardNo(memberCardNo);
        }

        orderDetail.setTransNo(trade_no);
        orderDetail.setAuthCode(sn);

        orderDetail.setPointAmount(pointAmount);
        orderDetail.setSerialNum(SystemUtil.getImsi(mContext));
        ;

        orderDetail.setCash(0);
        orderDetail.setBankAmount(caculateMoneyEntity.getRealMoney());

        orderDetail.save();
    }

    private void openConfirmDialog(int channel) {
        MyDialog.Builder builder = new MyDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage(EnumConsts.SqbPayChannel.getByType(channel).getName() + "收款成功！");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startActivity(new Intent(mContext, PayMoneyInputActivity.class));

                Intent intent = new Intent(PayMoneyInputActivity.RECEIVER_CLEAN_DATA_TAG);
                intent.putExtra(PayMoneyInputActivity.NOTIFY_CODE_TAG, PayMoneyInputActivity.CLEAN_DATA);
                sendBroadcast(intent);
                finish();
            }
        });
        builder.create().show();
    }

//    //自己生成订单号
//    public static String getNewClientSn(Context context, int payType_in, int scanPayType) {
//        String orderNo = "";
//        String device = "1";    //1:手机  2:Pos机
//        String payType = "" + payType_in;
//        String timestamp = TimeUtil.getCurrentDateString("yyyyMMddHHmmss");
//        String randomNum = StringUtil.createRandomStr("0123456789", 3);
//        String activateCode = "";
//        if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
//            activateCode = MyApplication.getmInstance().getLoginEntity().getActivateCode();
//        } else if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
//            activateCode = LocalParasUtils.getActivateCode(context);
//        }
//        orderNo = device + payType + timestamp + randomNum + activateCode;
//        return orderNo;
//    }

}
